package com.boc.ewr.bcimp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boc.ewr.bcimp.entity.CollCallList;
import com.boc.ewr.bcimp.service.ICollCallListService;
import com.boc.ewr.util.file.enumeration.ImportEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @Description: 智能催收会话明细
 * @Author: jeecg-boot
 * @Date: 2023-05-31
 * @Version: V1.0
 */
@Api(tags = "智能催收会话明细")
@RestController
@RequestMapping("/bcimp/collCallList")
@Slf4j
public class CollCallListController extends JeecgController<CollCallList, ICollCallListService> {
    @Autowired
    private ICollCallListService collCallListService;

    /**
     * 分页列表查询
     *
     * @param collCallList
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "智能催收会话明细-分页列表查询")
    @ApiOperation(value = "智能催收会话明细-分页列表查询", notes = "智能催收会话明细-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<CollCallList>> queryPageList(CollCallList collCallList,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        QueryWrapper<CollCallList> queryWrapper = QueryGenerator.initQueryWrapper(collCallList, req.getParameterMap());
        Page<CollCallList> page = new Page<CollCallList>(pageNo, pageSize);
        IPage<CollCallList> pageList = collCallListService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param collCallList
     * @return
     */
    @AutoLog(value = "智能催收会话明细-添加")
    @ApiOperation(value = "智能催收会话明细-添加", notes = "智能催收会话明细-添加")
    //@RequiresPermissions("com.boc.ewr:coll_call_list:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody CollCallList collCallList) {
        collCallListService.save(collCallList);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param collCallList
     * @return
     */
    @AutoLog(value = "智能催收会话明细-编辑")
    @ApiOperation(value = "智能催收会话明细-编辑", notes = "智能催收会话明细-编辑")
    //@RequiresPermissions("com.boc.ewr:coll_call_list:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody CollCallList collCallList) {
        collCallListService.updateById(collCallList);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "智能催收会话明细-通过id删除")
    @ApiOperation(value = "智能催收会话明细-通过id删除", notes = "智能催收会话明细-通过id删除")
    //@RequiresPermissions("com.boc.ewr:coll_call_list:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        collCallListService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "智能催收会话明细-批量删除")
    @ApiOperation(value = "智能催收会话明细-批量删除", notes = "智能催收会话明细-批量删除")
    //@RequiresPermissions("com.boc.ewr:coll_call_list:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.collCallListService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "智能催收会话明细-通过id查询")
    @ApiOperation(value = "智能催收会话明细-通过id查询", notes = "智能催收会话明细-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<CollCallList> queryById(@RequestParam(name = "id", required = true) String id) {
        CollCallList collCallList = collCallListService.getById(id);
        if (collCallList == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(collCallList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param collCallList
     */
    //@RequiresPermissions("com.boc.ewr:coll_call_list:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CollCallList collCallList) {
        return super.exportXls(request, collCallList, CollCallList.class, "智能催收会话明细");
    }


    /**
     * 通过批量导入excel数据
     */
    public Result<?> importExcel(List<String> showUrls, ImportEnum businessEnum) throws FileNotFoundException {
        boolean tmepFlag = true;
        for (String filePath : showUrls) {
            CommonUtils.filterFileName(filePath);
            File file = FileUtils.getFile(filePath);

            FileInputStream fileInputStream = null;
            try {
                fileInputStream = FileUtils.openInputStream(file);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            BufferedInputStream in = new BufferedInputStream(fileInputStream);
            // 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CollCallList> list = ExcelImportUtil.importExcel(in, businessEnum.getEntityName(), params);

                long start = System.currentTimeMillis();
                //TODO 补充批量导入的数据
                List<CollCallList> result = arrangeInfo(list);
                //批量导入
                Object serviceObj = SpringContextUtils.getBean(businessEnum.getServiceName());
                Method method = businessEnum.getServiceName().getMethod("initSaveBatch", Collection.class, Boolean.class);
                method.invoke(serviceObj, result, tmepFlag);
                tmepFlag = false;
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒，数据行数：" + result.size());
            } catch (Exception e) {
                //update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
                String msg = e.getMessage();
                log.error(msg, e);
                if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
                    return Result.error("文件导入失败:有重复数据！");
                } else {
                    return Result.error("文件导入失败:" + e.getMessage());
                }

            } finally {
                try {
                    fileInputStream.close();
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入成功！");
    }

    private List<CollCallList> arrangeInfo(List<CollCallList> list) {
        String callId = "";
        String taskNm = "";
        String phoneNum = "";
        String callTag = "";
        String processNm = "";
        Date callTime = null;
        List<CollCallList> resultList = new ArrayList<>();
        for (CollCallList collCall : list) {
            callId = StringUtils.isEmpty(collCall.getCallId()) ? callId : collCall.getCallId();
            taskNm = StringUtils.isEmpty(collCall.getTaskNm()) ? taskNm : collCall.getTaskNm();
            phoneNum = StringUtils.isEmpty(collCall.getPhoneNum()) ? phoneNum : collCall.getPhoneNum();
            callTag = StringUtils.isEmpty(collCall.getCallTag()) ? callTag : collCall.getCallTag();
            processNm = StringUtils.isEmpty(collCall.getProcessNm()) ? processNm : collCall.getProcessNm();
            callTime = StringUtils.isEmpty(String.valueOf(collCall.getCallTime())) ? callTime : collCall.getCallTime();
            collCall.setCallId(callId);
            collCall.setTaskNm(taskNm);
            collCall.setPhoneNum(phoneNum);
            collCall.setCallTag(callTag);
            collCall.setProcessNm(processNm);
            collCall.setCallTime(callTime);
            resultList.add(collCall);
        }
        return resultList;
    }


}
